package com.ebookstore.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ebookstore.common.PagedListHolder;

public class SearchBooksAction extends BaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("SearchBooksAction.execute()");

		// 如果是查询
		if (request.getParameter("search") != null) {
			// 获得关键字
			String keyword = request.getParameter("keyword");
			// 如果关键字为空，则提示错误信息
			if (keyword == null || keyword.length() == 0) {
				request.setAttribute("message", "请输入关键字");
				return mapping.findForward("failure");
			} else {
				// 查询结果，并放入到分页器中
				List data = getEBookStore().getBookService().findBookByKeyword(
						keyword.toLowerCase());
				PagedListHolder bookList = new PagedListHolder(data);
				bookList.setPageSize(4);
				// 将分页器对象放入到Session中
				System.out.println("SearchBooksAction.execute():booklist "+bookList.getSource().get(0));
				request.getSession().setAttribute("SearchBooksAction_bookList",
						bookList);
				request.setAttribute("bookList", bookList);

				return mapping.findForward("success");
			}
		} else {
			// 如果是分页
			String page = request.getParameter("page");
			PagedListHolder bookList = (PagedListHolder) request.getSession()
					.getAttribute("SearchBooksAction_bookList");
			// 下一页
			if ("next".equals(page)) {
				bookList.nextPage();
			} else if ("previous".equals(page)) {// 上一页
				bookList.previousPage();
			}
			request.setAttribute("bookList", bookList);

			return mapping.findForward("success");
		}
	}

}
